<?php

class DowndetailController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='admin';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','add','edit','uploadfile','uploadimage','delall'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Downdetail;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Downdetail']))
		{
			$model->attributes=$_POST['Downdetail'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->d_id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Downdetail']))
		{
			$model->attributes=$_POST['Downdetail'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->d_id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$criteria=new CDbCriteria;
		
		 foreach($_GET as $key=>$val){
            $val = addslashes($val);
            if($key=="d_id"&&$val&&$val!="ID..")$criteria->addCondition("d_id  regexp '{$val}' ");
            if($key=="d_name"&&$val&&$val!="文件名..")$criteria->addCondition("d_name  regexp '{$val}' ");
		}
		$criteria->addCondition("d_isdel = 1");
		$pageSize=isset($_COOKIE['s_pagesize'])?$_COOKIE['s_pagesize']:"20";
        setcookie("ggnewslistreturnurl",$_SERVER['REQUEST_URI'],0,"/");
        $dataProvider = new CActiveDataProvider("Downdetail",array(
                        'criteria'=>$criteria,
                        'pagination'=>array(
                            'pageSize'=>$pageSize
                        ),
        ));
        $this->render('index',array(
            'dataProvider'=>$dataProvider,
        ));
	}


	/**
	 * Lists all models.
	 */
	public function actionAdd()
	{
		$model=new Downdetail;
		 if($_POST){
            $model->attributes = $_POST;
            $model->setAttribute("d_name",$_POST['d_name']);
            $model->setAttribute("d_source",$_POST['d_source']);
            $model->setAttribute("d_uploadtime",time());
            $model->setAttribute("d_operator",Yii::app()->user->id);
            $model->setAttribute("d_isdel",1);
			
            if($model->save()){
                Yii::app()->user->setFlash("message","上传成功");
                $this->redirect(array("downdetail/index"));
            }else{
				Yii::app()->user->setFlash("message","上传失败，请重试！");
			}
        }
		$this->render('add',array(
			'model'=>$model,
		));
	}
	
	/**
     *通过$id来修改当前公告新闻
     */
    public function actionEdit($id)
    {
        $model = $this->loadModel($id);
        if($_POST){
            $model->attributes = $_POST;
            $model->setAttribute("d_name",$_POST['d_name']);
            $model->setAttribute("d_source",$_POST['d_source']);
            $model->setAttribute("d_operator",Yii::app()->user->id);
            $model->setAttribute("d_isdel",1);
			
            if($model->save()){
                Yii::app()->user->setFlash("message","修改上传成功");
                $this->redirect(array("downdetail/index"));
            }else{
				Yii::app()->user->setFlash("message","修改上传失败，请重试！");
			}
        }
        $this->render('edit',array(
            'model'=>$model,
        ));
    }
	
	public function actionUploadfile() {
		$this->layout='upload';
		$this->pageTitle = "文件上传";
		$upsize=array(
			"size"=>1024*2000000,
            // 'pixel'=>'150x210',.
           // 'pixel'=>'500x450',//限制必须多大的象素
			'title'=>"10000000K"
		);
		$this->Upload($upsize,"文件");
	}
	
	public function actionUploadImage() {
		$this->layout='upload';
		$this->pageTitle = "文件上传";
		$upsize=array(
			"size"=>1024*2000000,
            // 'pixel'=>'150x210',.
           // 'pixel'=>'500x450',//限制必须多大的象素
			'title'=>"10000000K"
		);
		$filename = isset($_GET["filename"])?$_GET["filename"].'.jpg':'';
		$this->Upload($upsize,"图片",$filename);
	}
	
	private function Upload($upsize,$fname,$filename=''){
		$str="";
			$editid=isset($_GET["editid"])?$_GET["editid"]:''; //
			$nameid=isset($_GET["nameid"])?$_GET["nameid"]:''; //
		if (@is_uploaded_file($_FILES['upfile']['tmp_name'])){
			$upfile=$_FILES["upfile"];
			$name = date("YmdHis",time()).mt_rand(1000,9999);//$upfile["name"];
			$type = preg_replace("/[\"\']/","",$upfile["type"]);
			$size = $upfile["size"];
			$tmp_name = $upfile["tmp_name"];
			$error = $upfile["error"];
			$ok=0;
			if($fname=='文件'){
				switch ($type) {//文件格式可以在下面增加判断
					case 'application/x-zip-compressed' : 
					$name=$name.".zip";
					$ok=1;
					break;
                    case 'application/zip' : 
					$name=$name.".zip";
					$ok=1;
					break;
					case 'application/octet-stream' : 
					$name=$name.".rar";
					$ok=1;
					break;
                    
                    
                    
                    case 'thesis/x-zip-compressed' : 
					$name=$name.".zip";
					$ok=1;
					break;
                    case 'thesis/zip' : 
					$name=$name.".zip";
					$ok=1;
					break;
					case 'thesis/octet-stream' : 
					$name=$name.".rar";
					$ok=1;
					break;
					case 'application/msword' : 
					$name=$name.".doc";
					$ok=1;
					break;
					case 'application/octet-stream' : 
					$name=$name.".exe";
					$ok=1;
					break;
					case 'application/vnd.ms-powerpoint' : 
					$name=$name.".ppt";
					$ok=1;
					break;
					case 'application/vnd.ms-excel' : 
					$name=$name.".xls";
					$ok=1;
					break;
				}
			}else{
				switch ($type) {//图片格式可以在下面增加判断
					case 'image/pjpeg' : 
					$name=$name.".jpg";
					$ok=1;
					break;
					case 'image/jpeg' : 
					$name=$name.".jpg";
					$ok=1;
					break;
					case 'image/gif' :
					$name=$name.".gif";
					 $ok=1;
					break;
					case 'image/png' :
					$name=$name.".png";
					$ok=1;
					break;
					case 'image/x-png' :
					$name=$name.".png";
					$ok=1;
					break;
				}
			}
			if (@$ok!=1){
                $str= "<script>alert('{$fname}格式不正确,请重试');location.reload();</script>";
			}else{
                if ($size>$upsize['size']){
                    $str= "<script>alert('{$fname}过大,大小请小于{$upsize['title']}');location.reload();</script>";
                }else{
                    if($ok && $error=='0'){
                        $pixelcheck=true;
                        if($fname=='图片'){
                            $IMG= @getimagesize($tmp_name);
                            if(isset($upsize['pixel'])&&$IMG){
                                $pixelArr=explode("x",$upsize['pixel']);
                                if($IMG[0]==$pixelArr[0]&&$IMG[1]==$pixelArr[1]){
                                    
                                }else{
                                    $pixelcheck=false;
                                    $str= "<script>alert('上传失败,\\n当前图片像素为：{$IMG[0]}x{$IMG[1]}，\\n{$this->pageTitle}需要{$upsize['pixel']}');location.reload();</script>";
                                }
                               
                            }
                        }     
                        // echo $str;
                            // echo $size."|";
                            // echo $upsize['size'];exit;
                        if($pixelcheck){
							if(!$filename)$path = PIC_PATH.$name;else $path = $_SERVER['DOCUMENT_ROOT']."/images/sbanner/".$filename;
                            if(@move_uploaded_file($tmp_name,$path)){
								$str="<script>alert('上传成功');";
                                if($editid)$str="<script>alert('上传成功');window.opener.document.getElementById('".$editid."').value='".PIC_URL.$name."';";
                                if($nameid)$str .= "window.opener.document.getElementById('".$nameid."').value='".$name."';";
                                $str.="window.close();</script>";
                            }else{
                                $str= "<script>alert('上传失败，请重试！');location.reload();</script>";
                            }
                        }
                    }
                }
            }
		}
		$this->render('upload',array(
			"script"=>$str,
		
		));
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Downdetail('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Downdetail']))
			$model->attributes=$_GET['Downdetail'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Downdetail::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='downdetail-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
	
	/**
	 * 批量回收站删除
	 */
	public function actionDelall()
	{
	   if (Yii::app()->request->isPostRequest&&isset($_POST['selectdel'])&&$_POST['selectdel'])
	   {
			/*1:删除  2:恢复*/
            // $tid=isset($_POST['tid'])&&in_array($_POST['tid'],array(1,2))?$_POST['tid']:"2";
            
            
			$criteria= new CDbCriteria;
            $count = Downdetail::model()->updateAll(array('d_isdel'=>2),"d_id in ( ".join(",",$_POST['selectdel'])." )"); 
			if($count>0){  
			   echo "ok";  
			}
	   }
	   else
		 throw new CHttpException(400,'无效的请求。请不要再这样的要求。');
	}
}
